﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using KongMing.ORM.EFCore.EFModelExtension;
using KongMing.ORM.EFCore.Models;
using Microsoft.EntityFrameworkCore;

namespace KongMing.ORM.EFCore
{
    public class EFDBContext : DbContext
    {

        public DbSet<Book> Book { get; set; }
        public DbSet<BookStore> BookStore { get; set; }
        public DbSet<StoreBookStock> StoreBookStock { get; set; }

        public DbSet<UserInfo> UserInfo { get; set; }
        public DbSet<Project> Project { get; set; }

        //这里是配置
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //DbContextOptionsBuilder注入
            base.OnConfiguring(optionsBuilder);
            //设置连接字符串
            optionsBuilder.UseSqlServer("server=.;Database=KongMing.BookDB;Uid=km;Pwd=666;");
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //注入ModelBuilder
            base.OnModelCreating(modelBuilder);
            //获取当前程序集默认的是查找所有继承了IEntityTypeConfiguration的类
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);

            foreach (var mutableEntityType in modelBuilder.Model.GetEntityTypes())
            {
                if (mutableEntityType.ClrType == null)
                    continue;
            }

            string _namespace = "KongMing.ORM.EFCore.Models";
            var types = Assembly.GetExecutingAssembly().GetTypes()
                .Where(x => x.IsClass && x.Namespace == _namespace).ToList();
            modelBuilder.AddOutSoftsPreFix(types);
        }
    }
}
